import json
import io
from PIL import Image
import requests
from django.http import HttpResponseRedirect, request, JsonResponse
from django.shortcuts import render,redirect,get_object_or_404,HttpResponse
#登录认证
def get_domain_token(username,password):
    data = {
        "auth": {
         "identity": {
            "methods": [
                "password"
            ],
            "password": {
                "user": {
                    "name": username,
                    "domain": {
                        "name": "default"
                    },
                    "password": password
                }
            }
        }
    }
}
    url = "http://192.168.119.130:5000/v3/auth/tokens"
    result = requests.post(url, data=json.dumps(data))
    # 返回的token在 response header 里面
    return result
# 获取project范围token
def get_project_token(domain_token):
    data = {
        "auth": {
            "identity": {
                "methods": [
                    "token"
                ],
                "token": {
                    "id": domain_token
                }
            },
            "scope": {
                "project": {
                    "domain": {
                        "name": "default",
                    },
                    "name": "admin"
                }
            }
        }
    }
    url = "http://192.168.119.130:5000/v3/auth/tokens"
    result = requests.post(url, data=json.dumps(data))
    # 返回的token在 response header 里面
    return result
#列出容器
def container_list(project_token):
    url = "http://192.168.119.130:8080/v1/AUTH_f389ee38dc484e52b9d8b44d987d0ded?format=json"
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.get(url, headers=headers)
    return result
#新增容器，以及元数据信息
def container_add(project_token,container_name,meta_name):
    url = "http://192.168.119.130:8080/v1/AUTH_f389ee38dc484e52b9d8b44d987d0ded/%s"%(container_name)
    headers = {}
    headers["X-Auth-Token"] = project_token
    headers["X-Container-Meta-InspectedBy"] = meta_name
    result = requests.put(url, headers=headers)
    return result
#删除容器
def container_delete(project_token,container_name):
    url = "http://192.168.119.130:8080/v1/AUTH_f389ee38dc484e52b9d8b44d987d0ded/%s" % (container_name)
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.delete(url, headers=headers)
    return result
#预览容器
def container_detail(project_token,container_name):
    url = "http://192.168.119.130:8080/v1/AUTH_f389ee38dc484e52b9d8b44d987d0ded/%s?format=json" % (container_name)
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.get(url, headers=headers)
    return result

#获取文件内容
def object_get(project_token,container_name,object_name):
    url = "http://192.168.119.130:8080/v1/AUTH_f389ee38dc484e52b9d8b44d987d0ded/%s/%s" % (container_name,object_name)
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.get(url, headers=headers)
    return result

#文件上传
def object_uploads(project_token,container_name,object_name,content,content_type):
    url = "http://192.168.119.130:8080/v1/AUTH_f389ee38dc484e52b9d8b44d987d0ded/%s/%s" % (container_name, object_name)
    headers = {}
    headers["X-Auth-Token"] = project_token
    headers["Content-Type"] = content_type
    result = requests.put(url,data=content,headers=headers)
    return result
#文件下载
def object_downloads(project_token,container_name,object_name):
    url = "http://192.168.119.130:8080/v1/AUTH_f389ee38dc484e52b9d8b44d987d0ded/%s/%s" % (container_name, object_name)
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.get(url,headers=headers)
    return result
#文件删除
def object_deletes(project_token,container_name,object_name):
    url = "http://192.168.119.130:8080/v1/AUTH_f389ee38dc484e52b9d8b44d987d0ded/%s/%s" % (container_name,object_name)
    headers = {}
    headers["X-Auth-Token"] = project_token
    result = requests.delete(url, headers=headers)
    return result







#登录
def login(request):
      return render(request,'zgh0381/login.html')
#登录验证
def login_check(request):
    username = request.POST["username"]
    password = request.POST["password"]
    domain_res=get_domain_token(username,password)
    if domain_res.status_code == 201:
        request.session["user"] = username
        request.session["domain_token"] = domain_res.headers.get("X-Subject-Token")
        project_res = get_project_token(request.session.get("domain_token", None))
        request.session["project_token"] = project_res.headers.get("X-Subject-Token")
        return redirect("/zgh0381/index")
    else:
        return redirect('/zgh0381/login')
#首页
def index(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/zgh0381/login')
    else:
        resp = container_list(project_token)
        if resp.status_code == 200:
                request.session["list_containers"] = resp.json()
                return render(request,'zgh0381/index.html')
        else:
            return render(request, 'zgh0381/login.html')
#容器列表页
def list_containers(request):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/zgh0381/login')
    else:
        resp = container_list(project_token)
        if resp.status_code == 200:
            request.session["list_containers"] = resp.json()
            return render(request, 'zgh0381/container_list.html')
        else:
            return render(request, 'zgh0381/login.html')
#新增容器页
def add_containers(request):
    container_name = request.POST.get("containername")
    meta_name = request.POST.get("meta")
    project_token = request.session.get("project_token", None)
    containerrep = container_add(project_token,container_name,meta_name)
    if containerrep.status_code == 201:
        return JsonResponse({"info": 1})
    else:
        return render(request,'zgh0381/container_list.html')
#删除容器
def delete_container(request):
    containername = request.POST.get("containername")
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/zgh0381/login')
    else:
        res = container_delete(project_token,containername)
        if 200 <= res.status_code and res.status_code <= 299:
            return JsonResponse({"res": 1})
        else:
            return JsonResponse({"res": 0})
#文件列表
def object_list(request):
    return render(request,'zgh0381/object_list.html')
#容器详情页
def detail_container(request,containername):
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/zgh0381/login')
    else:
        result = container_detail(project_token,containername)
        if result.status_code == 200 or result.status_code == 204:
            request.session['container_detail'] = result.json()
            request.session['containername'] = containername
            return redirect('zhanggh0381:object_list')

#文件内容
def object_content(request):
    containername = request.POST.get("container_name")
    request.session["containername"] = containername
    objectname = request.POST.get("objectname")
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/zgh0381/login')
    else:
        rep = object_get(project_token, containername,objectname)
        if rep.status_code == 200:
             obj_content = rep.text
             return JsonResponse({"objcontent": obj_content})

#文件上传
def object_upload(request):
    #获取文件
    if request.method == "POST":
                myFile = request.POST['object_name']
                filename= str(myFile)
                suffix = filename[filename.rfind('.') + 1:]
                containername = request.session.get("containername", None)
                domain_token = request.session.get("domain_token", None)
                project_token = request.session.get("project_token", None)
                #打开文件内容
                if not (domain_token and project_token):
                    return redirect('/zgh0381/login')
                else:
                    if suffix == 'txt':
                        with open("D:\\upload\\" + myFile, 'rb') as local:
                            obj_content = local.read()
                        content_type = "text/plain; charset=utf-8"
                        rep = object_uploads(project_token, containername, myFile, obj_content, content_type)
                        if rep.status_code == 201:
                            img = 'txt.png'
                            request.session['img'] = img
                            return redirect("/zgh0381/detail_container/%s"% (containername))
                    elif suffix == 'png':
                        with open("D:\\upload\\" + myFile, 'rb') as local:
                            obj_data = local.read()
                        content_type = "image/png"
                        rep = object_uploads(project_token, containername, myFile, obj_data, content_type)
                        if rep.status_code == 201:
                            img = 'png.png'
                            request.session['img'] = img
                            return redirect("/zgh0381/detail_container/%s"% (containername))
                    elif suffix == 'docx':
                        with open("D:\\upload\\" + myFile, 'rb') as local:
                            obj_data = local.read()
                        content_type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                        rep = object_uploads(project_token, containername, myFile, obj_data, content_type)
                        if rep.status_code == 201:
                            img = 'docx.png'
                            request.session['img'] = img
                            return redirect("/zgh0381/detail_container/%s"% (containername))
                    elif suffix == 'pdf':
                        with open("D:\\upload\\" + myFile, 'rb') as local:
                            obj_data = local.read()
                        content_type = "application/pdf"
                        rep = object_uploads(project_token, containername, myFile, obj_data, content_type)
                        if rep.status_code == 201:
                            img = 'pdf.png'
                            request.session['img'] = img
                            return redirect("/zgh0381/detail_container/%s"% (containername))
                    elif suffix == 'mp4':
                        with open("D:\\upload\\" + myFile, 'rb') as local:
                            obj_data = local.read()
                        content_type = "video/mp4"
                        rep = object_uploads(project_token, containername, myFile, obj_data, content_type)
                        if rep.status_code == 201:
                            img = 'mp4.png'
                            request.session['img'] = img
                            return redirect("/zgh0381/detail_container/%s" % (containername))
                    elif suffix == 'mp3':
                        with open("D:\\upload\\" + myFile, 'rb') as local:
                            obj_data = local.read()
                        content_type = "audio/mpeg"
                        rep = object_uploads(project_token, containername, myFile, obj_data, content_type)
                        if rep.status_code == 201:
                            img = 'mp3.png'
                            request.session['img'] = img
                            return redirect("/zgh0381/detail_container/%s" % (containername))
                    else:
                        with open("D:\\upload\\" + myFile, 'rb') as local:
                            obj_content = local.read()
                        content_type = "image/jpeg"
                        rep = object_uploads(project_token, containername, myFile, obj_content, content_type)
                        if rep.status_code == 201:
                            img = 'jpg.png'
                            request.session['img'] = img
                            return redirect("/zgh0381/detail_container/%s"% (containername))
    else:
        return render(request,"zgh0381/object_list.html")

#文件下载
def object_download(request,object_name):
    containername = request.session.get("containername", None)
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    suffix=object_name[object_name.rfind('.') + 1:]
    if not (domain_token and project_token):
        return redirect('/zgh0381/login')
    else:
        r = HttpResponse(content_type='application/octet-stream')
        r['Content-Disposition'] = 'attachment;filename="{0}"'.format(object_name)
        resp = object_downloads(project_token,containername,object_name)
        if resp.status_code == 200:
            if suffix == 'txt':
                r.write(str(resp.text))
            elif suffix == 'jpg':
                byte_stream = io.BytesIO(resp.content)
                roiImg = Image.open(byte_stream)
                imgByteArr = io.BytesIO()
                roiImg.save(imgByteArr, format='jpeg')
                imgByteArr = imgByteArr.getvalue()
                r.write(imgByteArr)
            elif suffix == 'png':
                byte_stream = io.BytesIO(resp.content)
                roiImg = Image.open(byte_stream)
                imgByteArr = io.BytesIO()
                roiImg.save(imgByteArr, format='png')
                imgByteArr = imgByteArr.getvalue()
                r.write(imgByteArr)
            elif suffix == 'docx':
                r.write(resp.content)
            elif suffix == 'pdf':
                r.write(resp.content)
            elif suffix == 'mp4':
                r.write(resp.content)
            else:
                r.write(resp.content)
        return r
#文件删除
def delete_object(request):
    containername = request.POST.get("containername")
    objectname = request.POST.get("objectname")
    domain_token = request.session.get("domain_token", None)
    project_token = request.session.get("project_token", None)
    if not (domain_token and project_token):
        return redirect('/zgh0381/login')
    else:
        res = object_deletes(project_token,containername,objectname)
        if res.status_code == 204:
            return JsonResponse({"info": 1})


